package com.taihe.thread;

/**
 * Created by zwt on 2018/10/31.
 * 测试线程间的通信
 */
public class Breads {

    private int id;

    private int num; //个数


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public Breads(int id, int num) {
        this.id = id;
        this.num = num;
    }

    public Breads(){
        super();
    }

    //生产的方法
    public synchronized void product() {
        if (0 != num) {
            //如果个数不为0 线程等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            num = num + 1;
            id = id + 1;
            String name = Thread.currentThread().getName();
            System.out.println(name + "生产了一个编号为" + id + "的产品");
            notify();//当执行完了之后去唤醒其他线程
        }
    }

    //消费的方法
    public synchronized void consume() {
        //如果个数为0 线程等待
        if (0 == num) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            num = num - 1;
            String name = Thread.currentThread().getName();
            System.out.println(name + "消费了一个编号为" + id + "的产品");
            notify();//当执行完了之后去唤醒其他线程
        }
    }


}
